﻿namespace ImageProcessing
{
    using System;
    using System.Collections.Generic;
    using System.Drawing;
    using System.Drawing.Imaging;
    using System.IO;
    using System.Linq;
    using System.Text;
    using System.Threading;
    using System.Windows.Forms;
    using CustomControlTrial;
    using ImageProcessing;


    /// <summary>
    /// Digital Image Class Contains all Ditgital Image attributes and Functions
    /// </summary>
    public class DImage
    {
        #region declaration
        /// <summary>   
        /// Number of all Images Orginal and Copies ( 1 and 1 ) 
        /// </summary>
        private static int imagesCount = 0;

        /// <summary>
        /// 2D array represent the image
        /// </summary>
        private ImageStructure[,] imageStructArray;

        /// <summary>
        /// 2D array represent the temp image needed for sum operations
        /// </summary>
        private ImageStructure[,] tempStructArray;

        /// <summary>
        /// Bitmap of the image
        /// </summary>
        private Bitmap imageBitmap;

        /// <summary>
        /// The Form which the Image Represents in
        /// </summary>
        private PicForm form;

        /// <summary>
        /// Unique ID for the image
        /// </summary>
        private int id = -1;

        /// <summary>
        /// Name of the image
        /// </summary>
        private string name;

        /// <summary>
        /// Width of the image
        /// </summary>
        private int width;

        /// <summary>
        /// Height of the image
        /// </summary>
        private int height;

        /// <summary>
        /// Extension (type) of the image
        /// </summary>
        private string extenstion;

        /// <summary>
        /// Path of the image
        /// </summary>
        private string filePath;

        /// <summary>
        /// shaps darw in this iamge
        /// </summary>
        private ShapeDraw myShaps = new ShapeDraw();

        /// <summary>
        /// Boolean to check if image is greyscale
        /// </summary>
        private bool greyScale = false;

        /// <summary>
        /// history of image
        /// </summary>
        private History imageHistory = new History();

        /// <summary>
        /// Carrying the tab in the container
        /// </summary>
        private CustomControlTrial.PHTab tab;

        /// <summary>
        /// Tabcontainer that contains the tab
        /// </summary>
        private CustomControlTrial.PHTabContainer tabcontainer;

        #endregion

        private bool isVideo;

        public bool IsVideo
        {
            get { return isVideo; }
            set { isVideo = value; }
        }

        private bool videoProcessing;

        public bool VideoProcessing
        {
            get { return videoProcessing; }
            set { videoProcessing = value; }
        }

        private int numberOfFrames;

        public int NumberOfFrames
        {
            get { return numberOfFrames; }
            set { numberOfFrames = value; }
        }

        private int currFrameIndex;

        public int CurrFrameIndex
        {
            get { return currFrameIndex; }
            set { currFrameIndex = value; }
        }

        /// <summary>
        /// Initializes a new instance of the DImage class.
        /// </summary>
        /// <param name="path">The path.</param>
        public DImage(string VideoPath)
        {
            this.filePath = VideoPath;
            this.isVideo = true;
            this.GetImageName();
            this.GetImageExtension();
            if (!this.OpenNewImage())
            {
                return;
            }

            this.tempStructArray = new ImageStructure[this.height, this.width];// hat el 7atagaat de beta3et awel frame
            this.imageStructArray = Operations.ConvertBitmapToStructure(this.imageBitmap);
            this.myShaps = new ShapeDraw();
            this.currFrameIndex = 0;
            // 3ashan el history

            // PS: momken to7ot frame 3'eer awel frame 3ala asas awel frame dayman eswed fe mo3zam el videos we7na 3awzeen frame ye2dar el user yshoof 3aleh el effects
                // momken te5leh ydoos play w lamma yewa2af ya5od el current frame w te3mel ll Dimage update bel current frame
           //  PS2: fel update hatndy 3ala update 3ady 5ales .. 3ashan ye3del fel sora elly el user shyefha .. w ba3deen tendah 3ala el function el hat3del fel video 
            // PS3: fehmt menak enak hat3dal 3ala el video el asasy .. mat3del fe copy w howa momken yesaveha fel a5er .
            // PS4: zawet kam satr fel function openImage beta3et el video
            // PS5: bas 5alas :D:D

            this.GetImageID();
            DImage newImage = new DImage(this.imageStructArray, this.imageHistory.HistoryList.Count.ToString(), this.width, this.height, this.id);
            this.imageHistory.HistoryList.Add(newImage);
            Main.currentInHistoryView = Main.CurrImage;

            Main.Instance.PHPictureStringList1.RemoveFrom(-1);
            CustomControlTrial.PHPictureString phpicstring = new CustomControlTrial.PHPictureString();


            newImage.GetImageBitmap();
            phpicstring.Picture.Image = newImage.imageBitmap;
            newImage.name = "Open";
            phpicstring.Lbl_Text.Text = newImage.name;
            Main.Instance.PHPictureStringList1.Checkable = false;
            Main.Instance.PHPictureStringList1.AddHistory(phpicstring);

        }

        public DImage(Bitmap bmp)
        {
            this.isVideo = false;
            this.name = "Captured frame";
            this.extenstion = "bmp";

            this.tempStructArray = new ImageStructure[this.height, this.width];// hat el 7atagaat de beta3et awel frame
            this.imageStructArray = Operations.ConvertBitmapToStructure(bmp);
            this.GetImageBitmap();
            this.myShaps = new ShapeDraw();
            // 3ashan el history

            this.width = bmp.Width;
            this.height = bmp.Height;

            this.GetImageID();
            DImage newImage = new DImage(this.imageStructArray, this.imageHistory.HistoryList.Count.ToString(), this.width, this.height, this.id);
            this.imageHistory.HistoryList.Add(newImage);
            Main.currentInHistoryView = Main.CurrImage;

            Main.Instance.PHPictureStringList1.RemoveFrom(-1);
            CustomControlTrial.PHPictureString phpicstring = new CustomControlTrial.PHPictureString();


            newImage.GetImageBitmap();
            phpicstring.Picture.Image = newImage.imageBitmap;
            newImage.name = "Open";
            phpicstring.Lbl_Text.Text = newImage.name;
            Main.Instance.PHPictureStringList1.Checkable = false;
            Main.Instance.PHPictureStringList1.AddHistory(phpicstring);
        }

        /// <summary>
        /// Initializes a new instance of the DImage class.
        /// </summary>
        /// <param name="path">The path.</param>
        /// <param name="enumMode">The enum mode.</param>
        public DImage(string path, ref EditingMode enumMode)
        {
            this.filePath = path;
            this.GetImageName();
            this.GetImageExtension();
            if (!this.OpenNewImage())
            {
                return;
            }

            this.GetImageWidth();
            this.GetImageHeight();
            this.tempStructArray = new ImageStructure[this.height, this.width];
            this.GetImageID();
            this.GetImageBitmap();
            this.BackupImageArray();
            this.myShaps = new ShapeDraw();
            this.form = new PicForm(this);

            // this.form.Show();
            DImage newImage = new DImage(this.imageStructArray, this.imageHistory.HistoryList.Count.ToString(), this.width, this.height, this.id);
            this.imageHistory.HistoryList.Add(newImage);
            Main.currentInHistoryView = Main.CurrImage;

            Main.Instance.PHPictureStringList1.RemoveFrom(-1);
            CustomControlTrial.PHPictureString phpicstring = new CustomControlTrial.PHPictureString();
            //phpicstring.Started = true;

            newImage.GetImageBitmap();
            phpicstring.Picture.Image = newImage.imageBitmap;
            newImage.name = "Open";
            phpicstring.Lbl_Text.Text = newImage.name;
            Main.Instance.PHPictureStringList1.Checkable = false;
            Main.Instance.PHPictureStringList1.AddHistory(phpicstring);

        }

        /// <summary>
        /// Initializes a new instance of the DImage class.
        /// </summary>
        public DImage()
        {
            this.imageStructArray = null;
            this.imageBitmap = null;
            this.name = null;
            this.extenstion = null;
            this.filePath = null;
            this.form = null;
            this.width = 0;
            this.height = 0;
            this.GetImageID();
            this.BackupImageArray();
            DImage newImage = new DImage(this.imageStructArray, this.imageHistory.HistoryList.Count.ToString(), this.width, this.height, this.id);
            this.imageHistory.HistoryList.Add(newImage);
            this.Tab = null;
        }

        /// <summary>
        /// Initializes a new instance of the <see cref="DImage"/> class.
        /// </summary>
        /// <param name="newImage">The new image.</param>
        /// <param name="name">The name.</param>
        /// <param name="width">The width.</param>
        /// <param name="height">The height.</param>
        /// <param name="id">The id.</param>
        public DImage(ImageStructure[,] newImage, string name, int width, int height, int id)
        {
            this.imageStructArray = Operations.CopyImage(newImage, width, height);
            this.name = name;
            this.width = width;
            this.height = height;
            this.id = id;
            this.imageHistory.HistoryList.Add(this);

        }

        /// <summary>
        /// Gets the images count.
        /// </summary>
        public static int ImagesCount
        {
            get { return DImage.imagesCount; }
        }

        /// <summary>
        /// Gets or sets the im history.
        /// </summary>
        /// <value>
        /// The im history.
        /// </value>
        public History ImHistory
        {
            get { return this.imageHistory; }
            set { this.imageHistory = value; }
        }

        /// <summary>
        /// Gets or sets the tab.
        /// </summary>
        /// <value>
        /// The tab.
        /// </value>
        public CustomControlTrial.PHTab Tab
        {
            get { return this.tab; }
            set { this.tab = value; }
        }

        /// <summary>
        /// Gets or sets the height1.
        /// </summary>
        /// <value>
        /// The height1.
        /// </value>
        public int Height1
        {
            get { return this.height; }
            set { this.height = value; }
        }

        /// <summary>
        /// Gets or sets the width1.
        /// </summary>
        /// <value>
        /// The width1.
        /// </value>
        public int Width1
        {
            get { return this.width; }
            set { this.width = value; }
        }

        /// <summary>
        /// Gets or sets my shaps.
        /// </summary>
        /// <value>
        /// My shaps.
        /// </value>
        public ShapeDraw MyShaps
        {
            get { return this.myShaps; }
            set { this.myShaps = value; }
        }

        /// <summary>
        /// Gets or sets the image struct array.
        /// </summary>
        /// <value>
        /// The image struct array.
        /// </value>
        public ImageStructure[,] ImageStructArray
        {
            get { return this.imageStructArray; }
            set { this.imageStructArray = value; }
        }

        /// <summary>
        /// Gets the temp struct array1.
        /// </summary>
        public ImageStructure[,] TempStructArray1
        {
            get { return this.tempStructArray; }
        }

        /// <summary>
        /// Gets or sets the image bitmap.
        /// </summary>
        /// <value>
        /// The image bitmap.
        /// </value>
        public Bitmap ImageBitmap
        {
            get { return this.imageBitmap; }
            set { this.imageBitmap = value; }
        }

        /// <summary>
        /// Gets or sets the form1.
        /// </summary>
        /// <value>
        /// The form1.
        /// </value>
        public PicForm Form1
        {
            get { return this.form; }
            set { this.form = value; }
        }

        /// <summary>
        /// Gets or sets the id.
        /// </summary>
        /// <value>
        /// The id.
        /// </value>
        public int Id
        {
            get { return this.id; }
            set { this.id = value; }
        }

        /// <summary>
        /// Gets or sets the name.
        /// </summary>
        /// <value>
        /// The name.
        /// </value>
        public string Name
        {
            get { return this.name; }
            set { this.name = value; }
        }

        /// <summary>
        /// Gets the width.
        /// </summary>
        public int Width
        {
            get { return this.width; }
            set { this.width = value; }
        }

        /// <summary>
        /// Gets the height.
        /// </summary>
        public int Height
        {
            get { return this.height; }
            set { this.height = value; }
        }

        /// <summary>
        /// Gets the extenstion.
        /// </summary>
        public string Extenstion
        {
            get { return this.extenstion; }
        }

        /// <summary>
        /// Gets the file path.
        /// </summary>
        public string FilePath
        {
            get { return this.filePath; }
        }

        /// <summary>
        /// Gets or sets a value indicating whether [grey scale].
        /// </summary>
        /// <value>
        ///   <c>true</c> if [grey scale]; otherwise, <c>false</c>.
        /// </value>
        public bool GreyScale
        {
            get { return this.greyScale; }
            set { this.greyScale = value; }
        }

        /// <summary>
        /// Decreases the images count.
        /// </summary>
        public static void DecreaseImagesCount()
        {
            imagesCount--;
        }

        /// <summary>
        /// Updates the image attributes to match the specified image array.
        /// </summary>
        /// <param name="imageArray">The image array.</param>
        public void UpdateImage(ImageStructure[,] imageArray)
        {
            this.imageStructArray = imageArray;
            this.UpdateImage();
        }

        /// <summary>
        /// Updates the image attributes.
        /// </summary>
        public void UpdateImage()
        {
            if (this.videoProcessing)
            {
                this.ImageBitmap = Operations.DisplayMatrix(this.imageStructArray);
                return;
            }

            this.GetImageWidth();
            this.GetImageHeight();
            this.GetImageBitmap();

            DImage newImage = new DImage(this.imageStructArray, Main.OperationName, this.width, this.height, this.id);
            this.imageHistory.AddToHistory(newImage);
            newImage.GetImageBitmap();



            if (Main.currentInHistoryView == Main.CurrImage)
            {
                CustomControlTrial.PHPictureString phpicstring = new CustomControlTrial.PHPictureString();
                //phpicstring.Started = true;
                phpicstring.Picture.Image = newImage.imageBitmap;
                phpicstring.Lbl_Text.Text = newImage.name;
                Main.Instance.PHPictureStringList1.Checkable = false;
                Main.Instance.PHPictureStringList1.AddHistory(phpicstring);
            }
            else
            {
                Main.Instance.PHPictureStringList1.RemoveFrom(-1);

                foreach (DImage item in this.ImHistory.HistoryList)
                {
                    CustomControlTrial.PHPictureString phpicstring = new CustomControlTrial.PHPictureString();
                    //phpicstring.Started = true;
                    phpicstring.Picture.Image = item.imageBitmap;
                    phpicstring.Lbl_Text.Text = item.name;
                    Main.Instance.PHPictureStringList1.Checkable = false;
                    Main.Instance.PHPictureStringList1.AddHistory(phpicstring);
                }
            }

            Main.SelectedIndexChange = true;
            Main.Instance.PHPictureStringList1.ActiveIndex = this.ImHistory.HistoryList.Count - 1;
            if (this.form != null)
            {
                this.form.UpdateForm(this.imageBitmap);
            }

            this.UpdateTab();
            Main.HistoChart.Updatehisto(this);
            Main.UpdateChannelsPic();
            ((PHPictureString)Main.channels.Controls[0]).IsCheckedWithoutEvent(true);
            ((PHPictureString)Main.channels.Controls[1]).IsCheckedWithoutEvent(true);
            ((PHPictureString)Main.channels.Controls[2]).IsCheckedWithoutEvent(true);
            ((PHPictureString)Main.channels.Controls[3]).IsCheckedWithoutEvent(true);
        }

        /// <summary>
        /// Clones the image for copy image.
        /// </summary>
        /// <returns>new cloned image</returns>
        public DImage CloneImage()
        {
            this.GetImageWidth();
            this.GetImageHeight();
            this.GetImageBitmap();

            DImage newImage = new DImage(this.imageStructArray, Main.OperationName, this.width, this.height, this.id);
            this.imageHistory.AddToHistory(newImage);

            // if (this.form != null)
            // {
            //    this.form.UpdateForm(this.imageBitmap);
            // }
            // this.OpenNewImage();
            return newImage;
        }

        /// <summary>
        /// Updates the history image.
        /// </summary>
        /// <param name="imageArray">The image array.</param>
        public void UpdateHistoryImage(ImageStructure[,] imageArray)
        {
            this.imageStructArray = imageArray;
            this.GetImageWidth();
            this.GetImageHeight();
            this.GetImageBitmap();
            if (this.form != null)
            {
                // this.form.UpdateForm(this.imageBitmap);
                this.form.UpdateForm(Operations.DisplayMatrix(imageArray));
            }

            this.UpdateTab();
            Main.HistoChart.Updatehisto(this);
            Main.UpdateChannelsPic();
            ((PHPictureString)Main.channels.Controls[0]).IsCheckedWithoutEvent(true);
            ((PHPictureString)Main.channels.Controls[1]).IsCheckedWithoutEvent(true);
            ((PHPictureString)Main.channels.Controls[2]).IsCheckedWithoutEvent(true);
            ((PHPictureString)Main.channels.Controls[3]).IsCheckedWithoutEvent(true);
        }

        /// <summary>
        /// Backups the image array.
        /// </summary>
        public void BackupImageArray()
        {
            this.tempStructArray = Operations.CopyImage(this.imageStructArray, this.width, this.height);
        }

        /// <summary>
        /// Retrives the image array.
        /// </summary>
        public void RetriveImageArray()
        {
            this.ImageStructArray = Operations.CopyImage(this.TempStructArray1, this.width, this.height);
            this.UpdateImage();
        }

        /// <summary>
        /// Sets the tab.
        /// </summary>
        /// <param name="tabControl">The tab control.</param>
        public void SetTab(CustomControlTrial.PHTabContainer tabControl)
        {
            tabControl.Add(this.name);
            PictureBox picBox = new PictureBox();
            picBox.SizeMode = PictureBoxSizeMode.AutoSize;
            picBox.Image = this.imageBitmap;
            picBox.MouseMove += new MouseEventHandler(ImageEvents.Image_MouseMove);
            picBox.MouseUp += new MouseEventHandler(ImageEvents.Image_MouseUp);
            picBox.MouseDown += new MouseEventHandler(ImageEvents.Image_MouseDown);
            picBox.MouseWheel += new MouseEventHandler(ImageEvents.Image_MouseWheel);
            picBox.MouseClick += new MouseEventHandler(ImageEvents.Image_MouseClick);
            picBox.MouseDoubleClick += new MouseEventHandler(ImageEvents.Image_MouseDoubleClick);
            picBox.SizeChanged += new EventHandler(picBox_SizeChanged);
            // picBox.ContextMenuChanged += new MouseEventHandler(ImageEvents.Image_KeyPress);
            picBox.MouseEnter += new EventHandler(ImageEvents.Image_MouseEnter);
            picBox.MouseLeave += new EventHandler(ImageEvents.Image_MouseLeave);
            picBox.Paint += new PaintEventHandler(ImageEvents.Image_Paint);
            this.Tab = tabControl.tabs[tabControl.tabs.Count - 1];
            this.Tab.Panel.Controls.Add(picBox);
            this.Tab.Visible = true;
            this.Tab.BringToFront();
            tabControl.UpdateViewPanel();
            this.tabcontainer = tabControl;
            UpdatePcbLocation();
        }

        /// <summary>
        /// Updates the tab.
        /// </summary>
        public void UpdateTab()
        {
            PictureBox pcb = (PictureBox)this.tabcontainer.tempPanel.Controls[0];
            pcb.Image = this.imageBitmap;

            // pcb.SizeMode = PictureBoxSizeMode.CenterImage;
            // pcb.Size = tab.Panel.Size;
            // tabcontainer.UpdateViewPanel();
        }

        /// <summary>
        /// Gets the name of the image.
        /// </summary>
        private void GetImageName()
        {
            string[] pathParts = this.filePath.Split("\\"[0]);
            this.name = pathParts[pathParts.Length - 1];
        }

        /// <summary>
        /// Gets the image extension.
        /// </summary>
        private void GetImageExtension()
        {
            string[] fileExtension = this.filePath.Split('.');
            this.extenstion = fileExtension[1];
        }

        /// <summary>
        /// Opens a new image.
        /// </summary>
        /// <returns> True if a supported file is Chosen .. False otherwise </returns>
        private bool OpenNewImage()
        {
            string[] fileData = this.filePath.Split('.');
            bool format8 = false;
            if (fileData[fileData.GetLength(0) - 1].ToLower() == "bmp" || fileData[fileData.GetLength(0) - 1].ToLower() == "jpeg" || fileData[fileData.GetLength(0) - 1].ToLower() == "jpg" || fileData[fileData.GetLength(0) - 1].ToLower() == "gif" || fileData[fileData.GetLength(0) - 1].ToLower() == "png")
            {
                this.imageStructArray = OpenImage.LoadBMP(this.filePath, out format8);
                this.GreyScale = format8;
            }
            else if (fileData[fileData.GetLength(0) - 1].ToLower() == "pgm")
            {
                this.imageStructArray = OpenImage.OpenP5Image(this.filePath, out format8);
                this.GreyScale = format8;
            }
            else if (fileData[fileData.GetLength(0) - 1].ToLower() == "ppm")
            {
                // P6
                TextReader tr = new StreamReader(this.filePath);
                string firstLine = tr.ReadLine();
                tr.Close();
                if (firstLine.ToLower() == "p3")
                {
                    this.imageStructArray = OpenImage.OpenP3Image(this.filePath);
                }
                else if (firstLine.ToLower() == "p6")
                {
                    this.imageStructArray = OpenImage.LoadP6(this.filePath);
                }
                else
                {
                    MessageBox.Show("Invalid file, please select a new one!");
                    return false;
                }
            }
            else if (fileData[fileData.GetLength(0) - 1].ToLower() == "avi" || fileData[fileData.GetLength(0) - 1].ToLower() == "mpg" || fileData[fileData.GetLength(0) - 1].ToLower() == "mpeg" || fileData[fileData.GetLength(0) - 1].ToLower() == "wmv" || fileData[fileData.GetLength(0) - 1].ToLower() == "mp4")
            {
                int width = 0, height = 0, numberOfFrames = 0;
                int capture = 2;
                PHVideoCapture.PHInitializeCapture((this.filePath + '\0').ToArray(), ref width, ref height, ref numberOfFrames, ref capture);

                if (capture == 0)
                {
                    MessageBox.Show("Video capture failed!");
                    return false;
                }

                this.width = width;
                this.height = height;
                this.numberOfFrames = numberOfFrames;

                this.imageBitmap = new Bitmap(width, height, PixelFormat.Format24bppRgb);
                PHVideoCapture.QueryFrame(this.imageBitmap);
            }
            else
            {
                MessageBox.Show("Invalid file, please select a new one!");
                return false;
            }

            return true;
        }

        /// <summary>
        /// Gets the width of the image.
        /// </summary>
        private void GetImageWidth()
        {
            this.width = this.imageStructArray.GetLength(1);
        }

        /// <summary>
        /// Gets the height of the image.
        /// </summary>
        private void GetImageHeight()
        {
            this.height = this.imageStructArray.GetLength(0);
        }

        /// <summary>
        /// Gets the image ID.
        /// </summary>
        private void GetImageID()
        {
            this.id = imagesCount++;
        }

        /// <summary>
        /// Gets the image bitmap.
        /// </summary>
        private void GetImageBitmap()
        {
            this.imageBitmap = Operations.DisplayMatrix(this.imageStructArray);
        }

        public void UpdateImage(Bitmap Bmp)
        {
            if (this.videoProcessing)
            {
                this.ImageBitmap = Bmp;
                return;
            }

            this.imageBitmap = Bmp;
            PictureBox pcb = (PictureBox)this.tabcontainer.tempPanel.Controls[0];
            pcb.Image = this.imageBitmap;

            UpdatePcbLocation();
            this.GetImageWidth();
            this.GetImageHeight();
            this.imageStructArray = Operations.ConvertBitmapToStructure(Bmp);

            DImage newImage = new DImage(this.imageStructArray, Main.OperationName, this.width, this.height, this.id);
            this.imageHistory.AddToHistory(newImage);
            newImage.GetImageBitmap();



            if (Main.currentInHistoryView == Main.CurrImage)
            {
                CustomControlTrial.PHPictureString phpicstring = new CustomControlTrial.PHPictureString();
                //phpicstring.Started = true;
                phpicstring.Picture.Image = newImage.imageBitmap;
                phpicstring.Lbl_Text.Text = newImage.name;
                Main.Instance.PHPictureStringList1.Checkable = false;
                Main.Instance.PHPictureStringList1.AddHistory(phpicstring);
            }
            else
            {
                Main.Instance.PHPictureStringList1.RemoveFrom(-1);

                foreach (DImage item in this.ImHistory.HistoryList)
                {
                    CustomControlTrial.PHPictureString phpicstring = new CustomControlTrial.PHPictureString();
                    //phpicstring.Started = true;
                    phpicstring.Picture.Image = item.imageBitmap;
                    phpicstring.Lbl_Text.Text = item.name;
                    Main.Instance.PHPictureStringList1.Checkable = false;
                    Main.Instance.PHPictureStringList1.AddHistory(phpicstring);
                }
            }

            Main.SelectedIndexChange = true;
            Main.Instance.PHPictureStringList1.ActiveIndex = this.ImHistory.HistoryList.Count - 1;
            if (this.form != null)
            {
                this.form.UpdateForm(this.imageBitmap);
            }

            Main.HistoChart.Updatehisto(this);
            Main.UpdateChannelsPic();
            ((PHPictureString)Main.channels.Controls[0]).IsCheckedWithoutEvent(true);
            ((PHPictureString)Main.channels.Controls[1]).IsCheckedWithoutEvent(true);
            ((PHPictureString)Main.channels.Controls[2]).IsCheckedWithoutEvent(true);
            ((PHPictureString)Main.channels.Controls[3]).IsCheckedWithoutEvent(true);
        }

        public void UpdatePcbLocation()
        {
            PictureBox picBox = (PictureBox)tabcontainer.tempPanel.Controls[0];
            picBox.Location = new Point((tabcontainer.tempPanel.Width / 2) - (picBox.Width / 2), (tabcontainer.tempPanel.Height / 2) - (picBox.Height / 2));
            if (picBox.Location.X < 0 && picBox.Location.Y < 0)
            {
                picBox.Location = new Point(0, 0);
            }
            else if (picBox.Location.X < 0)
            {
                picBox.Location = new Point(0, picBox.Location.Y);
            }
            else if (picBox.Location.Y < 0)
            {
                picBox.Location = new Point(picBox.Location.X, 0);
            }
        }

        public DImage(int height, int width, Color clr, string iName)
        {
            this.filePath = null;
            this.Name = iName;
            this.height = height;
            this.width = width;
            this.extenstion = null;
            this.imageBitmap = new Bitmap(width, height);
            BitmapData bmpd = this.imageBitmap.LockBits(new Rectangle(0, 0, this.imageBitmap.Width, this.imageBitmap.Height), ImageLockMode.ReadWrite, PixelFormat.Format24bppRgb);
            int extraBytes = bmpd.Stride - bmpd.Width * 3;
            PHFastCpp.PHBitmapFill((int)bmpd.Scan0, extraBytes, this.width, this.height, clr.B, clr.G, clr.R);
            this.imageBitmap.UnlockBits(bmpd);
            this.imageStructArray = Operations.ConvertBitmapToStructure(this.ImageBitmap);
            this.GetImageID();
            this.BackupImageArray();
            this.myShaps = new ShapeDraw();
            this.form = new PicForm(this);

            // this.form.Show();
            DImage newImage = new DImage(this.imageStructArray, this.imageHistory.HistoryList.Count.ToString(), this.width, this.height, this.id);
            this.imageHistory.HistoryList.Add(newImage);
            Main.currentInHistoryView = Main.CurrImage;

            Main.Instance.PHPictureStringList1.RemoveFrom(-1);
            CustomControlTrial.PHPictureString phpicstring = new CustomControlTrial.PHPictureString();
            //phpicstring.Started = true;

            newImage.GetImageBitmap();
            phpicstring.Picture.Image = newImage.imageBitmap;
            newImage.name = "New";
            phpicstring.Lbl_Text.Text = newImage.name;
            Main.Instance.PHPictureStringList1.Checkable = false;
            Main.Instance.PHPictureStringList1.AddHistory(phpicstring);

        }

        private void picBox_SizeChanged(object sender, EventArgs e)
        {
            UpdatePcbLocation();
        }
    }
}